package org.fastsyncer.connector.sqlserver;

import org.fastsyncer.common.entity.BaseInfo;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.connector.common.DatabaseConstant;
import org.fastsyncer.connector.framework.AbstractDatabaseConnector;
import org.fastsyncer.connector.util.DatabaseUtil;
import org.springframework.jdbc.core.JdbcTemplate;

public final class SqlServerConnector extends AbstractDatabaseConnector implements SqlServer {

    private static volatile SqlServerConnector instance = null;

    private SqlServerConnector() {
    }

    public static SqlServerConnector getInstance() {
        if (null == instance) {
            synchronized (SqlServerConnector.class) {
                if (null == instance) {
                    instance = new SqlServerConnector();
                }
            }
        }
        return instance;
    }
    
    @Override
    public BaseInfo getBaseInfoConnector(DatabaseConfig config, String queryFilter) {
        JdbcTemplate jdbcTemplate = DatabaseUtil.getJdbcTemplate(config);
        String table = config.getTable().toUpperCase();
        // 查询元信息 SELECT TOP 0 * FROM USER
        String metaSQL = new StringBuilder().append("SELECT ").append(DatabaseConstant.SQLSERVER_PAGE_SQL_NULL).append(" * FROM ").append(table).toString();
        // 求数据总量 SELECT * FROM USER WHERE ID='123'
        String countSQL = new StringBuilder().append("SELECT * FROM ").append(table).append(queryFilter).toString();
        BaseInfo connector = DatabaseUtil.getDataSourceConnector(jdbcTemplate, metaSQL, countSQL);
        // 释放连接
        DatabaseUtil.close(jdbcTemplate);
        return connector;
    }

    @Override
    public StringBuilder getPageSQL(DatabaseConfig config, StringBuilder sql) {
        // SqlServer 分页查询
        // 获取表名和主键
        String table = config.getTable().toUpperCase();
        String pk = config.getPrimaryKey().toUpperCase();
        // sql> SELECT * FROM SD_USER
        // sql> SELECT * FROM SD_USER ORDER BY USER.ID OFFSET(3-1) * 1000 ROWS FETCH NEXT 1000 ROWS ONLY
        sql.append(" ORDER BY ").append(table).append(".").append(pk).append(" OFFSET(?-1) * ? ROWS FETCH NEXT ? ROWS ONLY");
        return sql;
    }

}
